/*
 * MIT License
 *
 * Copyright (c) 2020 wen.gu <454727014@qq.sys>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

 /***************************************************************************
  * Name: deserializer.h
  *
  * Purpose: deserializer implementation for 'SYS' Functional
  *
  * Developer:
  *   wen.gu , 2020-06-12
  *
  * TODO:
  *
  ***************************************************************************/

  /******************************************************************************
   **    INCLUDES
   ******************************************************************************/
#ifndef __PANDA_COM_DESERIALIZER_H__
#define __PANDA_COM_DESERIALIZER_H__

#include <array>
#include <vector>
#include <memory>
#include <string>
#include <stdint.h>

#include "panda/sys/sys_types.h"
#include "panda/sys/ipc_types.h"
#include "panda/core/utils.h"
/******************************************************************************
 **    MACROS
 ******************************************************************************/

/******************************************************************************
 **    TYPE DEFINITIONS
 ******************************************************************************/
namespace panda
{
namespace sys 
{

namespace internal_impl
{
/** for check target has member function: void Deserialize(Deserializer& dsr); */
template<typename T, typename... Args>
struct has_member_deserialize
{
private:
    template<typename U> static auto Check(int) -> decltype(std::declval<U>().Deserialize(std::declval<Args>()...), std::true_type());
    template<typename U> static std::false_type Check(...);
public:
    //static constexpr auto value = decltype(Check<T>(0))::value;
    enum { value = std::is_same<decltype(Check<T>(0)), std::true_type>::value };
};
} /** namespace internal_impl */
/******************************************************************************
**    CLASSES/FUNCTIONS DEFINITIONS
******************************************************************************/

class SYS_CLASS Deserializer final
{
public:
    using DataByteOrder = panda::core::DataByteOrder;
public:
    Deserializer(PayloadPtr data, uint32_t size, DataByteOrder byteOrder = panda::core::GetPlatformByteOrder());
    ~Deserializer();

public:
    bool read(bool& value);
    bool read(uint8_t& value);
    bool read(uint16_t& value);
    bool read(uint32_t& value);
    bool read(uint64_t& value);
    bool read(int8_t& value);
    bool read(int16_t& value);
    bool read(int32_t& value);
    bool read(int64_t& value);
    bool read(float& value);
    bool read(double& value);
    bool read(std::string& value);
    bool read(uint8_t* data, uint32_t size);
public:

    template<typename T>
    bool read(const std::vector<T>& val)
    {/** treat Optional as dynamic array, |val.size()| element values...| */
        bool ret = false;
        uint32_t size;
        if (read(size))
        {
            ret = true;
            for (size_t i; i < size; i++)
            {
                T tmp;
                if (Read(tmp))
                {
                    val.push_back(tmp);
                }
                else
                {
                    ret = false;
                    val.clear();
                    break;
                }
            }
        }

        return ret;
    }

    template<typename T, std::size_t N>
    bool read(const std::array<T, N>& val)
    {
        bool ret = false;
        uint32_t size;
        if (read(size))
        {
            if (size <= N)
            {
                ret = true;
                for (size_t i; i < size; i++)
                {
                    T tmp;
                    if (Read(tmp))
                    {
                        val.push_back(tmp);
                    }
                    else
                    {
                        ret = false;
                        val.clear();
                        break;
                    }
                }
            }
        }

        return ret;
    }

    template<typename T, typename std::enable_if<std::is_enum<T>::value >::type >
    bool read(T& val) /** write for enum */
    {
        return read((typename internal_impl::enum2Int<sizeof(T)>::type&)(val));
    }

    template<typename T, typename std::enable_if<internal_impl::has_member_deserialize<T, const Deserializer&>::value >::type >
    bool read(T& val) /** write for struct */
    {/** every struct need provide a template method:
      * template<typename T>
      * Serialize(const T& ser) const;
      */
        return val.Deserialize(*this); /**todo, refineme */
    }

private:
    class impl;
    std::unique_ptr<impl> mImpl;
};

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

using DeserializerPtr = std::shared_ptr<Deserializer>;
} /** namespace sys */
} /** namespace panda */


#endif /** !__PANDA_COM_DESERIALIZER_H__ */
